#coding=utf-8
import os
import subprocess
import locale
import codecs

"""
需要安装inotify windows版本
github地址： https://github.com/thekid/inotify-win
安装ossutil 工具
工具地址：  https://help.aliyun.com/document_detail/50452.html?spm=a2c4g.11186623.6.1259.b768779cymuYWx
ossutil 配置好默认的oss  endpoint access-key-id  access-key-secret  

"""

localpath = "E:\\inotify\\"
#拼接 inotifywait 命令
command = 'inotifywait.exe -rmq -e create --format "%%e-%%w\%%f-%%T" {}'.format(
    localpath)
ossutil = 'D:\\Software\\ossutil64\\ossutil64.exe cp -r -f '

osspath = ' oss://yfrelease/img3/ossutilstest/'

ps = subprocess.Popen(
    command,
    shell=True,
    close_fds=True,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE)
while True:
    data = ps.stdout.readline()
    if data == b'':
        if ps.poll() is not None:
            break
    else:
        #返回事件信息
        info = data.decode(codecs.lookup(locale.getpreferredencoding()).name)
        #分割出文件名
        filename = info.split("-")[1]
        #去除前路径，只保留当前目录中的路径
        ossname=filename.replace(localpath,'')
        #将windows路径转换为 Unix路径
        ossname=ossname.replace('\\','/')
        #拼接ossutil 命令
        cmd = '{}{}{}'.format(ossutil,filename,"{}{}".format(osspath,ossname))
        #执行命令
        os.system(cmd)

